﻿using Dora.Tools.Utility.Const;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Dora.Tools.Utility.Redis
{
    /// <summary>
    /// 缓存员工可以访问的系统菜单
    /// </summary>
    public class SystemMenuCacheHelper
    {
        private const string pre_key = DoraRedisKey.SysMenuPre;//redis 缓存key前缀
        private const int expire_seconds = 600;//缓存10分钟
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static string GetRedisKey(string systemKey, Guid userId)
        {
            var key = $"{pre_key}{systemKey}_{userId}";
            return key;
        }

        /// <summary>
        /// 缓存用户访问某个系统的菜单
        /// </summary>
        /// <returns></returns>
        public static async Task Set(string systemKey, Guid userId, List<dynamic> list)
        {
            var key = GetRedisKey(systemKey,userId);
            await RedisManager.SetAsync(key, list, expire_seconds);
        }

        /// <summary>
        /// 获取缓存的用户访问某个系统的菜单
        /// </summary>
        /// <returns></returns>
        public static async Task<List<dynamic>> Get(string systemKey, Guid userId)
        {
            var key = GetRedisKey(systemKey, userId);
            if (await RedisManager.ExistsAsync(key))
            {
                RedisManager.Expire(key, expire_seconds);
                return await RedisManager.GetAsync<List<dynamic>>(key);
            }
            else
            {
                return null;
            }
        }
        
        /// <summary>
        /// 存在就刷新用户访问某个系统的菜单
        /// </summary>
        /// <returns></returns>
        public static async Task<bool> Exist(string systemKey, Guid userId)
        {
            var key = GetRedisKey(systemKey, userId);
            if (await RedisManager.ExistsAsync(key))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
